﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Logging;

namespace Highlearner
{
	public partial class FormSettings : Form
	{
		public FormSettings()
		{
			InitializeComponent();
		}

		private void FormSettings_Load(object sender, EventArgs e)
		{
			// Initialize the combo box
			foreach (CInstitutes.SInstitute l_oInst in CInstitutes.Institutes.Values)
			{
				comboBoxInstitute.Items.Add(l_oInst.Name);
			}

			comboBoxInstitute.SelectedIndex = Highlearner.Properties.Settings.Default.Institute;
			textBoxDownloadsDirectory.Text = Highlearner.Properties.Settings.Default.SavePath;

			textBoxUsername.Text = Highlearner.Properties.Settings.Default.Username;

			// Decrypt the password from the settings
			string l_sPass = Highlearner.Properties.Settings.Default.Password;

			if (l_sPass.Trim().Length != 0)
			{
				textBoxPassword.Text = Utilities.CAESEncyption.Decrypt(l_sPass);
			}

			checkBoxRememberUsername.Enabled = !checkBoxDontRememberSettings.Checked;
		}

		private bool CheckUsername()
		{
			if (Properties.Settings.Default.Username == "")
			{
				errorProvider1.SetError(textBoxUsername, "אנא הכנס שם משתמש");
				return false;
			}
			else
			{
				errorProvider1.SetError(textBoxDownloadsDirectory, "");
				return true;
			}
		}

		private void buttonOK_Click(object sender, EventArgs e)
		{
			// Update settings
			Highlearner.Properties.Settings.Default.Institute = comboBoxInstitute.SelectedIndex;
			Highlearner.Properties.Settings.Default.SavePath = textBoxDownloadsDirectory.Text;

			string l_sPass = textBoxPassword.Text;
			string l_sEncryptedPassword = "";

			if (l_sPass.Trim().Length != 0)
			{
				l_sEncryptedPassword = Utilities.CAESEncyption.Encrypt(l_sPass);
			}

			if (!Highlearner.Properties.Settings.Default.ForgetSettings)
			{
				Highlearner.Properties.Settings.Default.Save();
			}

			Highlearner.Properties.Settings.Default.Password = l_sEncryptedPassword;
			Highlearner.Properties.Settings.Default.Username = textBoxUsername.Text;

			if (!CheckUsername())
			{
				return;
			}

			if ((Highlearner.Properties.Settings.Default.SaveUserDetails) && (!Properties.Settings.Default.ForgetSettings))
			{
				Highlearner.Properties.Settings.Default.Save();
			}

			this.DialogResult = DialogResult.OK;
			Close();
		}

		private void FormSettings_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyData == Keys.Enter)
			{
				e.Handled = true;
				buttonOK.PerformClick();
			}
		}

		private bool CheckDownloadsPath(string a_sPath)
		{
			try
			{
				if (!(Directory.Exists(a_sPath)))
				{
					Directory.CreateDirectory(a_sPath);
				}
				FileStream l_oFile = File.Create(a_sPath + "\\Test.dat");
				l_oFile.Close();
				File.Delete(a_sPath + "\\Test.dat");

				return true;
			}
			catch (UnauthorizedAccessException e)
			{
				String l_sMessage = "מיקום זה הוא מיקום מוגן" + "\n" + "אם ברצונך לשמור למיקום זה בכל זאת, אנא הרץ את התוכנה שנית עם הרשאות אדמיניסטרציה";
				MessageBox.Show(l_sMessage, "Access Denied", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				CLogger.LogMessage(e.Message);
			}
			catch (Exception)
			{
				CLogger.LogMessage("Path is invalid. Failed creating directory. Reverted to the original path");	
			}

			return false;
		}

		private void buttonOpenDownloadsDirectory_Click(object sender, EventArgs e)
		{
			FolderBrowserDialog l_oDialog = new FolderBrowserDialog();

			l_oDialog.ShowNewFolderButton = true;
			l_oDialog.SelectedPath = textBoxDownloadsDirectory.Text;

			if (l_oDialog.ShowDialog() == DialogResult.OK)
			{
				if (CheckDownloadsPath(l_oDialog.SelectedPath))
				{
					textBoxDownloadsDirectory.Text = l_oDialog.SelectedPath;
				}
			}
		}

		private void textBoxUsername_TextChanged(object sender, EventArgs e)
		{
			if (textBoxUsername.Text != "")
			{
				errorProvider1.SetError(textBoxUsername, "");
			}
		}

		private void buttonCheckConnection_Click(object sender, EventArgs e)
		{
			if (CheckUsername())
			{

			}
		}

		private void checkBoxDontRememberSettings_CheckedChanged(object sender, EventArgs e)
		{
			checkBoxRememberUsername.Enabled = !checkBoxDontRememberSettings.Checked;
		}
	}
}
